<template>
  <div>
    <el-row>
      <el-button type="primary" @click="openDialog()" label-position="left">新增推荐类别</el-button>
      <el-dialog
        :title="dialogType==='add'?'新增图片推荐类别':'编辑推荐类别'"
        :visible.sync="dialogFormVisible"
        :before-close="closeDialog"
      >
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="类别名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入类别名称"></el-input>
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
            <el-input v-model="form.sort" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="是否开启" :label-width="formLabelWidth" prop="status">
            <el-select v-model="form.status" filterable placeholder="请选择状态" style="width:100%">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐类型" :label-width="formLabelWidth" prop="recommend_type">
            <el-select v-model="form.recommend_type" placeholder="请选择推荐类型" style="width:100%">
              <el-option
                v-for="item in recommendTypes"
                :key="item.recommend_type"
                :label="item.label"
                :value="item.recommend_type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="跳转类型" :label-width="formLabelWidth" prop="link_type">
            <el-select
              v-model="form.link_type"
              placeholder="请选择跳转类型"
              style="width:100%"
              @change="changeTypes"
            >
              <el-option
                v-for="item in changeOptions"
                :key="item.link_type"
                :label="item.label"
                :value="item.link_type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="跳转链接"
            ref="link"
            :label-width="formLabelWidth"
            v-if="form.link_type==4"
            prop="link"
          >
            <el-input v-model="form.link" placeholder="请输入跳转链接"></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.link_type&&form.link_type!=4"
            :label="form.link_type==1?'跳转分类':form.link_type==2?'跳转标签':form.link_type==3?'跳转专题':''"
            :label-width="formLabelWidth"
            prop="link_name"
          >
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==1"
              style="width:100%;"
              :fetch-suggestions="queryCategory"
              placeholder="请输入分类id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==2"
              style="width:100%;"
              :fetch-suggestions="queryTags"
              placeholder="请输入标签id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==3"
              style="width:100%;"
              :fetch-suggestions="queryTopic"
              placeholder="请输入专题id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog()">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogType=='add'?addRecommendCategory('form'):submitEdit('form')"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-row>
    <el-table
      :default-sort="{prop: 'sort', order: 'ascending'}"
      row-key="id"
      ref="multipleTable"
      :data="recommendCategoryList"
      tooltip-effect="dark"
      style="width: 100%;margin-top:15px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="name" label="文案名称"></el-table-column>
      <el-table-column prop="recommend_type" label="推荐类型">
        <template slot-scope="scope">
          <p>{{parseInt(scope.row.recommend_type)|recommendTypeFilter}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="link_type" label="跳转类型">
        <template slot-scope="scope">
          <p>{{parseInt(scope.row.link_type)|linkTypeFilter}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="link_id" label="跳转id/链接">
        <template slot-scope="scope">
          <div v-if="scope.row.link_type!=4">
            {{scope.row.link_type==1?'分类':scope.row.link_type==2?'标签':'专题'}}
            <span>-{{scope.row.link_name}} id：{{scope.row.link_id}}</span>
          </div>
          <div v-if="scope.row.link_type==4">
            链接：
            <a :href="scope.row.link" target="_blank">{{scope.row.link}}</a>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="50"></el-table-column>
      <el-table-column prop="status" label="显示状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.statusBool"
            active-text="开启"
            inactive-text="关闭"
            @change="suggestStatusChange($event, scope.row.id)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="编辑修改" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button @click="deleteRecommended(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import Sortable from "sortablejs";
import { typeSelects } from "@/utils/sel_dict";
import { queryCategory, queryTags, queryTopic } from "@/utils/query";
export default {
  data() {
    return {
      selectlinkId: "", //选中的id
      recommendTypes: [
        {
          recommend_type: 1,
          label: "热门用途"
        },
        {
          recommend_type: 2,
          label: "热门风格"
        },
        {
          recommend_type: 3,
          label: "精选素材"
        }
      ],
      rules: {
        name: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        recommend_type: [
          { required: true, message: "请选择推荐类别", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        link: [
          {
            required: true,
            message: "请填写跳转类型ID/链接",
            trigger: "change"
          }
        ],
        link_id: [
          { required: true, message: "请输入跳转类型id", trigger: "blur" }
        ],
        link_type: [
          { required: true, message: "请输入跳转类型", trigger: "change" }
        ],
        link_name: [
          {
            required: true,
            message: "请选择对应的跳转ID/链接",
            trigger: "change"
          }
        ]
      },
      changeOptions: typeSelects,
      recommendCategoryList: [],
      dataList: [],
      multipleSelection: [],
      dialogFormVisible: false,
      dialogType: "add",
      formLabelWidth: "120px",
      form: {
        id: "",
        name: "", //专题名称
        recommend_type: "", //推荐类型
        status: 0, //状态0关闭，1开启
        sort: "", //排序
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_type: "", //链接类型
        link_name: ""
      },
      options: [
        {
          value: 0,
          label: "开启"
        },
        {
          value: 1,
          label: "关闭"
        }
      ]
    };
  },
  created() {},
  mounted() {
    this.getRecommendCategory();
    this.rowDrop();
  },
  methods: {
    queryCategory(...args) {
      return queryCategory.call(this, ...args);
    },
    queryTags(...args) {
      return queryTags.call(this, ...args);
    },
    queryTopic(...args) {
      return queryTopic.call(this, ...args);
    },
    //选中某个ID跳转
    handleSelectLink(item) {
      if (item.id == -1) {
        this.form.link_id = "";
        this.form.link_name = "";
        return;
      }
      this.form.link_id = item.id;
      this.form.link = "";
    },
    changeTypes() {
      this.form.link = "";
      this.form.link_id = "";
      this.form.link_name = "";
    },
    openDialog() {
      this.axios.get("/recommend/getRecommendCount").then(res => {
        this.form.sort = res + 1;
        this.dialogType = "add";
        this.dialogFormVisible = true;
      });
    },
    // 定义事件获取subtabbar传递过来的dataList值
    passSelected(val) {
      this.dataList = val;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    initForm() {
      return (this.form = {
        id: "",
        name: "", //专题名称
        recommend_type: "", //推荐类型
        status: 0, //状态0关闭，1开启
        sort: "", //排序
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_type: "", //链接类型
        link_name: ""
      });
    },
    closeDialog() {
      this.initForm();
      this.dialogFormVisible = false;
      this.$refs.form.resetFields();
    },

    // 打开编辑专题
    handleEdit(item) {
      this.dialogFormVisible = true;
      this.dialogType = "edit";
      Object.assign(this.form, item);
    },

    //行拖拽排序
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        draggable: ".el-table__row",
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.recommendCategoryList.splice(oldIndex, 1)[0];
          _this.recommendCategoryList.splice(newIndex, 0, currRow);
          if (newIndex === oldIndex) {
            return;
          }
          _this.axios
            .post("/recommend/recommendSort", {
              params: {
                start: newIndex,
                end: oldIndex
              }
            })
            .then(res => {
              if (res != undefined) {
                _this.$message.success("已经更新顺序");
                _this.getRecommendCategory();
              } else {
                _this.$message.error("排序失败");
              }
            });
        }
      });
    },

    // 提交编辑
    submitEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.link_type !== 4 && this.form.link_id == "") {
            this.$message.info(
              "跳转内容有误，请在输入后点击输入框提示的内容！"
            );
            return false;
          }
          this.axios({
            method: "post",
            url: "/recommend/editRecommendCategory",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.dialogFormVisible = false;
                this.closeDialog();
                this.getRecommendCategory();
                this.$message.success("编辑成功");
              } else {
                this.$message.success("编辑失败");
              }
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },

    addRecommendCategory(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.link_type !== 4 && this.form.link_id == "") {
            this.$message.info(
              "跳转内容有误，请在输入后点击输入框提示的内容！"
            );
            return false;
          }
          this.axios({
            method: "post",
            url: "/recommend/addRecommendCategory",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.dialogFormVisible = false;
                this.closeDialog();
                this.getRecommendCategory();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },

    // 删除推荐分类
    deleteRecommended(item) {
      this.$confirm(`是否删除 "${item.name}" 专题?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.axios({
            url: "/recommend/deleteRecommended",
            method: "post",
            data: item
          }).then(res => {
            if (res) {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.getRecommendCategory();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 获取推荐类别数据
    getRecommendCategory() {
      this.axios({
        method: "get",
        url: "/recommend/getRecommendCategory"
      })
        .then(res => {
          for (let row of res.rows) {
            row.statusBool = row.status == 0;
          }
          this.recommendCategoryList = res.rows;
        })
        .catch(err => {
          console.log(err);
        });
    },
    suggestStatusChange(v, id) {
      this.axios
        .post("/recommend/modifyCategoryStatus", { id: id, status: v ? 0 : 1 })
        .then(res => {
          if (res) {
            if (v) {
              this.$message.info("已开启");
            } else {
              this.$message.info("已关闭");
            }
            this.getRecommendCategory();
          }
        })
        .catch(() => {
          this.$message.error("设置失败");
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.move {
  border: 1px solid #ddd;
  border-radius: 3px;
  width: 100%;
  height: 100%;
}
</style>